package org.example.treeletter.controller;

import org.example.treeletter.entity.Comment;
import org.example.treeletter.entity.Message;
import org.example.treeletter.entity.User;
import org.example.treeletter.repository.CommentRepository;
import org.example.treeletter.repository.UserRepository;
import org.example.treeletter.service.MessageService;

import org.example.treeletter.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/api")
public class MessageController {

    private static final Logger logger = LoggerFactory.getLogger(MessageController.class);

    @Autowired

    private UserService userService;

    private final MessageService messageService;

    public MessageController(MessageService messageService) {
        this.messageService = messageService;
    }

    @Autowired
    private CommentRepository commentRepository;

    @PostMapping("/messages")
    public String saveMessage(@RequestBody MessageRequest request) {
        logger.info("Received request: {}", request);
        try {
            messageService.saveMessage(request.getSign(), request.getContent(), request.getUserId());
            return "信件发送成功";
        } catch (Exception e) {
            logger.error("Error saving message", e);
            throw e;
        }
    }

    @GetMapping("/messages")
    public ResponseEntity<List<Message>> getMessagesByUserId(@RequestParam Integer userId) {
        List<Message> messages = messageService.getMessagesByUserId(userId);
        return ResponseEntity.ok(messages);
    }
    @PostMapping("/messages/{messageID}/comment")
    public ResponseEntity<String> addComment(@PathVariable Integer messageID,
                                             @RequestBody CommentRequest request) {
        if (request.getCommentText() == null || request.getCommentText().trim().isEmpty()) {
            return ResponseEntity.badRequest().body("评论文本不能为空");
        }
        try {
            // 假设 messageService 中有一个方法可以接收 userId
            messageService.addComment(messageID, request.getCommentText(), request.getUserId(),request.getUserPhone(),request.getCreationTime());
            return ResponseEntity.ok("评论添加成功");
        } catch (Exception e) {
            logger.error("Error adding comment", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误");
        }
    }

    @GetMapping("/messages/{messageID}/comment")
    public ResponseEntity<List<Comment>> getCommentsForMessage(@PathVariable Integer messageID) {
        List<Comment> comments = messageService.getCommentsForMessage(messageID);
        return ResponseEntity.ok(comments);
    }
    @DeleteMapping("/messages/{messageID}")
    public String deleteMessage(@PathVariable Integer messageID) {
        messageService.deleteMessageById(messageID);
        return "信件删除成功";
    }

    @DeleteMapping("/messages/comment/{commentID}")
    public String deleteComment(@PathVariable Integer commentID) {
        try {
            messageService.deleteCommentById(commentID);
            return "留言删除成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "留言删除失败";
        }
    }

    //获取单个消息的详细信息
    @GetMapping("/messages/{messageID}")
    public ResponseEntity<Message> getMessageDetails(@PathVariable Integer messageID) {
        logger.info("Fetching message details for ID: {}", messageID);
        Message messageDetails = messageService.getMessageById(messageID);
        if (messageDetails == null) {
            return ResponseEntity.notFound().build(); // 返回404 Not Found
        }
        return ResponseEntity.ok(messageDetails); // 返回200 OK和消息详情
    }

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/login")
    public ResponseEntity<UserResponse> login(@RequestBody User user) {
        User existingUser = userRepository.findByPhone(user.getPhone());

        if (existingUser != null && existingUser.getPassword().equals(user.getPassword())) {
            UserResponse response = new UserResponse(existingUser.getUserId(), existingUser.getPhone());
            return ResponseEntity.ok(response);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // 返回401 Unauthorized
        }
    }
    @PostMapping("/register")
    public ResponseEntity<String> register(@RequestBody User user) {
        logger.info("Received registration request: {}", user);

        try {
            messageService.registerUser(user);
            return ResponseEntity.ok("注册成功");
        } catch (Exception e) {
            logger.error("Error during registration", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器内部错误");
        }
    }
    @GetMapping("/messages/random")
    public ResponseEntity<Message> getRandomMessage(
            @RequestParam(value = "userId", required = false) Integer userId) {
        logger.info("Fetching random message");

        // 如果userId为空，则可以返回null或抛出异常，具体根据业务需求决定
        if (userId == null) {
            return ResponseEntity.badRequest().build(); // 返回400 Bad Request
        }

        // 获取随机消息，排除当前用户的信件
        Message randomMessage = messageService.getRandomMessageExcludingUserId(userId);
        if (randomMessage == null) {
            return ResponseEntity.noContent().build(); // 返回204 No Content
        }
        return ResponseEntity.ok(randomMessage); // 返回200 OK和随机消息
    }



    // 将 MessageRequest 定义为静态内部类
    static class MessageRequest {
        private String sign;
        private String content;
        private Integer userId;

        public String getSign() {
            return sign;
        }

        public void setSign(String sign) {
            this.sign = sign;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public Integer getUserId() {
            return userId;
        }

        public void setUserId(Integer userId) {
            this.userId = userId;
        }
    }
    static class UserResponse {
        private Integer userId;
        private String phone;

        public UserResponse(Integer userId, String phone) {
            this.userId = userId;
            this.phone = phone;
        }

        public Integer getUserId() {
            return userId;
        }

        public String getPhone() {
            return phone;
        }
    }
}